import Vue from "vue";
import Router from "vue-router";
import store from "@/store";
import indexAdminRoute from "@/tool/adminRoute";
Vue.use(Router);

let router = new Router({
  base: process.env.BASE_URL,
  routes: [
    { path: "/", redirect: "/admin" },
    {
      path: "/admin",
      name: "admin",
      component: () => import("@/views/index.vue"),
      redirect: "/admin/login",
      children: [
        {
          path: "login",
          name: "adminLogin",
          component: () => import("@/views/login/index.vue")
        },
        indexAdminRoute
      ]
    },
    {
      path: "*",
      name: "notFound",
      component: () => import("@/views/notFound/index.vue")
    }
  ]
});
export default router;

router.beforeEach(function(to, from, next) {
  let arr = [];
  let lastShowMenuRoute = "";
  if (to.matched.length > 1) {
    to.matched.forEach(item => {
      // 面包屑动态修改
      if (to.matched[1].name === "adminIndex") {
        if (item.meta.name) {
          let obj = {
            router: item.name,
            name: item.meta.name,
            isShow: item.meta.showMenu
          };
          arr.push(obj);
          if (item.meta.showMenu) {
            lastShowMenuRoute = item.name;
          }
        }
      }
    });

    if (to.matched[1].name === "adminIndex") {
      // 只在刷新的时候获取sessionStorage的state
      if (from.matched.length === 0) {
        let aState = window.sessionStorage.getItem("aState");
        if (aState) {
          store.replaceState(JSON.parse(aState));
        }
      }
      store.dispatch("changeActiveMenu", lastShowMenuRoute);
      store.dispatch("changeCurrentBreadcrumb", arr);
      store.dispatch("changeCurrentRouter", arr[arr.length - 1].router);
      if (!arr[arr.length - 1].isShow) {
        store.dispatch("changeShowOperationPage", true);
      } else {
        store.dispatch("changeShowOperationPage", false);
      }
      let openKey = [];
      let openKeyString = arr[1].router;
      openKey.push(openKeyString);
      store.dispatch("changeOpenKey", openKey);
    }
  }
  next();
});
